package com.zhongxi.guoyuan.OffLineShop.UI;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.baidu.navisdk.adapter.BNCommonSettingParam;
import com.baidu.navisdk.adapter.BNOuterLogUtil;
import com.baidu.navisdk.adapter.BNOuterTTSPlayerCallback;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.zhongxi.guoyuan.OffLineShop.ConnectNet.NetWork;
import com.zhongxi.guoyuan.OffLineShop.DetailStoreFragment;
import com.zhongxi.guoyuan.OffLineShop.Model.StoreDetail;
import com.zhongxi.guoyuan.OffLineShop.OffLineBaseFragment;
import com.zhongxi.guoyuan.OffLineShop.UrlOffLine.RelativeUrl;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.utils.Constants;
import com.zhongxi.guoyuan.utils.SpUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.view.MainHomeActivity;
import com.zhongxi.guoyuan.view.user.LoginActivity;
import com.zhongxi.guoyuan.widget.view.MyScrollView;

import java.io.File;
import java.util.LinkedList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;

public class OffLineShopDetailActivtiy extends OffLineBaseActivity {

    //导航
    private static final String APP_FOLDER_NAME = "Meirongyuan";
    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    private String mSDCardPath = null;
    public static List<Activity> activityList = new LinkedList<Activity>();
    private final static int authBaseRequestCode = 1;
    private final static String authBaseArr[] =
            {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_FINE_LOCATION};

    private final static String authComArr[] = {Manifest.permission.READ_PHONE_STATE};
    /**
     * 内部TTS播报状态回传handler
     */
    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * 内部TTS播报状态回调接口
     */
    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

        @Override
        public void playEnd() {
        }

        @Override
        public void playStart() {
        }
    };

    @Bind(R.id.toolbar)
    Toolbar mToolbar;
    @Bind(R.id.fl_container)
    FrameLayout mFlContainer;
    private String mShopid;


    View lodingView; //加载中..
    View errorView;//加载失败
    View emptyView; //加载为空
    View soldoutview; //店铺下架


    @Override
    protected void init() {
        setContentView(R.layout.activity_store_detail_offline);
        ButterKnife.bind(this);
        mShopid = getIntent().getStringExtra("offlineshopid");
    }

    @Override
    protected void initActionBar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolbar.setNavigationIcon(R.mipmap.topback);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
    }

    /*将四种布局添加到帧布局中*/
    @Override
    protected void initView() {
        if (lodingView == null) {
            lodingView = UiUtils.inflate(R.layout.loadingview_layout);
        }
        if (errorView == null) {
            errorView = UiUtils.inflate(R.layout.errorview_layout);
            errorView.findViewById(R.id.page_bt).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    mFlContainer.removeView(errorView);
                    loading();
                }
            });
        }
        if (emptyView == null) {
            emptyView = UiUtils.inflate(R.layout.emptyview_layout);
        }
        if (soldoutview == null) {
            soldoutview = UiUtils.inflate(R.layout.soldoutview_layout);
        }

        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS) != PackageManager.PERMISSION_GRANTED) {
            //申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.MODIFY_AUDIO_SETTINGS, Manifest.permission.INTERNET, Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS}, 100);
        } else {
            mapNavi();//初始化百度导航
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == authBaseRequestCode) {
            for (int ret : grantResults) {
                if (ret == 0) {
                    continue;
                } else {
//                    Toast.makeText(StoreDetailActivity.this, "缺少导航基本的权限!", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            initNavi();
        } else if (requestCode == 100) {
            mapNavi();//初始化百度导航
        }
    }

    private void mapNavi() {
        activityList.add(this);
        // 打开log开关
        BNOuterLogUtil.setLogSwitcher(false);
        if (initDirs()) {
            initNavi();
        }
    }

    /**
     * 获取目录
     *
     * @return
     */
    private boolean initDirs() {
        mSDCardPath = getSdcardDir();
        if (mSDCardPath == null) {
            return false;
        }
        File f = new File(mSDCardPath, APP_FOLDER_NAME);
        if (!f.exists()) {
            try {
                f.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        return true;
    }

    private String getSdcardDir() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            return Environment.getExternalStorageDirectory().toString();
        }
        return null;
    }

    private boolean hasBasePhoneAuth() {
        PackageManager pm = getPackageManager();
        for (String auth : authBaseArr) {
            if (pm.checkPermission(auth, getPackageName()) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    private void initNavi() {

        BNOuterTTSPlayerCallback ttsCallback = null;

        if (android.os.Build.VERSION.SDK_INT >= 23) {

            if (!hasBasePhoneAuth()) {

                requestPermissions(authBaseArr, authBaseRequestCode);
                return;

            }
        }

        BaiduNaviManager.getInstance()
                .init(this, mSDCardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {
                    @Override
                    public void onAuthResult(int status, String msg) {
                        if (0 == status) {
//                    authinfo = "key校验成功!";
                        } else {
//                    authinfo = "key校验失败, " + msg;
                        }
                        runOnUiThread(new Runnable() {

                            @Override
                            public void run() {
//                        Toast.makeText(context, authinfo, Toast.LENGTH_LONG).show();
                            }
                        });
                    }

                    public void initSuccess() {
//                Toast.makeText(context, "百度导航引擎初始化成功", Toast.LENGTH_SHORT).show();
                        initSetting();
                    }

                    public void initStart() {
//                Toast.makeText(context, "百度导航引擎初始化开始", Toast.LENGTH_SHORT).show();
                    }

                    public void initFailed() {
//                Toast.makeText(context, "百度导航引擎初始化失败", Toast.LENGTH_SHORT).show();
                    }


                }, null, ttsHandler, ttsPlayStateListener);
    }

    private void initSetting() {
        // 设置是否双屏显示
        BNaviSettingManager.setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        // 设置导航播报模式
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // 是否开启路况
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);

        Bundle bundle = new Bundle();
        // 必须设置APPID，否则会静音
        bundle.putString(BNCommonSettingParam.TTS_APP_ID, Constants.BAIDUMAP_ID);
        BNaviSettingManager.setNaviSdkParam(bundle);
    }

    @Override
    protected void initNetWork() {
        mFlContainer.addView(lodingView, new FrameLayout.LayoutParams(-1, -1));
        NetWork();
    }

    private void NetWork() {
        unsubscribe();
        mDisposable = NetWork.getOffLineApi()
                .getStoreDetailApi(RelativeUrl.StoreDetail + MyApplication.getInstance().getUrl(),
                        MyApplication.getInstance().getCheck(false), mShopid)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<StoreDetail>() {
                    @Override
                    public void accept(StoreDetail storeDetail) throws Exception {
                        MyApplication.getInstance().setSpValue(storeDetail.getSafeobj());
                        if (storeDetail.getCode() == 1) {
                            if (storeDetail.getData() != null && !"".equals(storeDetail.getData())) {
                                mFlContainer.removeView(lodingView);
                                addFragment(storeDetail);
                            } else {
                                mFlContainer.removeView(lodingView);
                                mFlContainer.addView(emptyView, new FrameLayout.LayoutParams(-1, -1));
                            }
                        } else if (storeDetail.getCode() == 1201) {
                            mFlContainer.removeView(lodingView);
                            mFlContainer.addView(soldoutview, new FrameLayout.LayoutParams(-1, -1));
                        } else if (storeDetail.getCode() == 2816) {
                            logoutDialog();
                        } else {
                            ToastUtil.show(getString(R.string.loseData, storeDetail.getCode()));
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        mFlContainer.removeView(lodingView);
                        mFlContainer.addView(errorView, new FrameLayout.LayoutParams(-1, -1));
                    }
                });
    }

    private void logoutDialog() {
        final AlertDialog mDialog = new AlertDialog.Builder(this).create();
        View view = UiUtils.inflate(R.layout.dialog_logout);
        TextView tv_Iknow = (TextView) view.findViewById(R.id.tv_Iknow);
        tv_Iknow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                clearData();
            }
        });
        mDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                    if (mDialog != null && mDialog.isShowing()) {
                        mDialog.dismiss();
                        clearData();
                    }
                    return true;
                }
                return false;
            }
        });
        mDialog.setCanceledOnTouchOutside(false);
        mDialog.setView(view);
        mDialog.show();
    }

    private void clearData() {
        if (null != MyApplication.getInstance().getUserId() || !"".equals(MyApplication.getInstance().getUserId())) {
            MyApplication.getInstance().sharedPrefrences.edit().putString("phone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("userid", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("username", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("shopname", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rmb", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("silver", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("inner", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("hd", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("num", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("shareHolder", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putBoolean("privilege", false).commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("avatar", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardName", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardUserphone", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddress", "").commit();
            MyApplication.getInstance().sharedPrefrences.edit().putString("rewardAddressid", "").commit();
            SpUtils.getInstance().saveSp("shopid", "");
            SpUtils.getInstance().saveSp("mdffline", "");
            SpUtils.getInstance().saveSp("orderid", "");
            finish();
            startActivity(new Intent(UiUtils.getContext(), MainHomeActivity.class));
        }
    }

    Handler mHandler = new Handler();

    private void loading() {
        mFlContainer.addView(lodingView, new FrameLayout.LayoutParams(-1, -1));
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(500);
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            NetWork();
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }


    private void addFragment(StoreDetail storeDetail) {
        DetailStoreFragment mFragment = new DetailStoreFragment();
        Bundle mBundle = new Bundle();
        mBundle.putSerializable("storeDetail", storeDetail);
        mFragment.setArguments(mBundle);
        getSupportFragmentManager()
                .beginTransaction()
                .add(R.id.fl_container, mFragment)
                .commit();
    }
}
